﻿using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Conusic.Model.Audio.Server
{
    public class AudioServer
    {
        private readonly TcpListener server;
        private readonly IPAddress localAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
        private readonly Thread worker;


        /// <summary>
        /// Initializes a new instance of the <see cref="AudioServer"/> class.
        /// </summary>
        /// <param name="port">Working AudioServerPort for http server.</param>
        /// <param name="background"></param>
        public AudioServer(int port, bool background = true)
        {
            server = new TcpListener(localAddress, port);
            if (background)
            {
                worker = new Thread(Listen);
                worker.IsBackground = true;
                worker.Start();
            }else 
                Listen();
        }


        /// <summary>
        /// Releases tcp socket and abort working thread.
        /// </summary>
        ~AudioServer()
        {
            if (worker != null && worker.IsAlive)
            {
                worker.Abort();
            }

            if (server != null)
                server.Stop();
        }

        /// <summary>
        /// Start listen in main thread.
        /// </summary>
        private void Listen()
        {
            server.Start();
            while (true)
            {
                var client = server.AcceptTcpClient();
                new Interaction(client);
            }
        }
    }
}
